#pragma once

#include <iostream>
#include <string>
#include <cstdio>
#include <ctime>
#include <stdarg.h>
#include <fcntl.h>

#define LOGNUM 1024

#define DEBUG      0
#define NORMAL     1
#define WARNING    2
#define ERROR      3
#define FATAL      4

#define PATH "./log.txt"

std::string msg(int level)
{
    switch(level)
    {
        case DEBUG: return "DEBUG";
        case NORMAL: return "NORMAL";
        case WARNING: return "WARNING";
        case ERROR: return "ERROR";
        case FATAL: return "FATAL";
        default: return nullptr;
    }
}

void logMessage(int log_level, const char* format, ...)
{
    // int sock = open(PATH, O_RDWR|O_CREAT|O_APPEND, 0600);
    FILE* f = fopen(PATH, "a");
    //[等级][时间][消息]
    std::string logprefix;
    logprefix = "[" + msg(log_level) + "]" + "[" + std::to_string(time(nullptr)) + "]";

    va_list args;
    va_start(args, format);
    char logline[LOGNUM];
    
    vsnprintf(logline, sizeof(logline), format, args);

    std::string log = logprefix + logline;
    // log[log.size()-1] = "\n";
    std::cout << logprefix << logline << std::endl;
    // write(sock, (logprefix+logline).c_str(), (logprefix+logline).size());
    fprintf(f, "%s\n",log.c_str());
    fclose(f);
    // close(sock);
}